<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量操作"
    width="700px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
  >
    <div v-loading="loading" class="batch-operation-dialog">
      <!-- 选中文章信息 -->
      <el-card class="selected-articles" shadow="never">
        <template #header>
          <span class="card-title"
            >选中的文章 ({{ selectedArticles.length }} 篇)</span
          >
        </template>

        <div class="articles-list">
          <div
            v-for="article in selectedArticles"
            :key="article.id"
            class="article-item"
          >
            <div class="article-info">
              <div class="article-title">{{ article.title }}</div>
              <div class="article-meta">
                <span class="author">{{ article.authorName }}</span>
                <el-divider direction="vertical" />
                <span class="category">{{ article.categoryName }}</span>
                <el-divider direction="vertical" />
                <el-tag
                  :type="
                    ArticleManagementUtils.getStatusTagType(article.status)
                  "
                  size="small"
                >
                  {{ ArticleManagementUtils.getStatusText(article.status) }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 操作选择 -->
      <el-card class="operation-selection" shadow="never">
        <template #header>
          <span class="card-title">选择操作</span>
        </template>

        <el-form
          ref="operationFormRef"
          :model="operationForm"
          :rules="operationRules"
          label-width="100px"
        >
          <el-form-item label="操作类型" prop="operationType" required>
            <el-select
              v-model="operationForm.operationType"
              placeholder="请选择操作类型"
              style="width: 100%"
              size="large"
              @change="handleOperationChange"
            >
              <el-option
                v-for="option in availableOperations"
                :key="option.value"
                :label="option.label"
                :value="option.value"
                :class="`operation-option-${option.type}`"
              >
                <div class="operation-option" :data-type="option.type">
                  <div class="option-content">
                    <span class="option-label">{{ option.label }}</span>
                    <span class="option-description">{{
                      getOperationDescription(option.value)
                    }}</span>
                  </div>
                </div>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="操作备注" prop="remark">
            <el-input
              v-model="operationForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入操作备注（可选）"
              maxlength="300"
              show-word-limit
            />
          </el-form-item>

          <el-form-item v-if="needsReason" label="操作原因" prop="reason">
            <el-input
              v-model="operationForm.reason"
              type="textarea"
              :rows="2"
              placeholder="请输入操作原因"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="通知设置">
            <el-checkbox v-model="operationForm.sendNotification">
              发送操作结果通知给相关用户
            </el-checkbox>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 操作预览 -->
      <el-card class="operation-preview" shadow="never">
        <template #header>
          <span class="card-title">操作预览</span>
        </template>

        <div class="preview-content">
          <el-alert
            v-if="operationForm.operationType"
            :title="getPreviewTitle()"
            :description="getPreviewDescription()"
            :type="getPreviewType()"
            show-icon
            :closable="false"
          />
          <div v-else class="no-operation">
            <el-empty description="请先选择操作类型" :image-size="80" />
          </div>
        </div>
      </el-card>

      <!-- 风险提示 -->
      <el-card v-if="isHighRiskOperation" class="risk-warning" shadow="never">
        <template #header>
          <span class="card-title">
            <IconifyIconOnline icon="ep:warning" />
            风险提示
          </span>
        </template>

        <el-alert
          title="高风险操作"
          description="此操作可能对文章产生重大影响，请谨慎操作并确认无误后再执行。"
          type="warning"
          show-icon
          :closable="false"
        />
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          :disabled="!operationForm.operationType"
          @click="handleSubmit"
        >
          执行操作
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  batchOperateArticlesApi,
  type ArticleInfo,
  type BatchOperationParams,
  BatchOperationType,
  ArticleManagementUtils
} from "@/api/article-management";
import { BATCH_OPERATION_OPTIONS, MESSAGES } from "@/constants/article";

defineOptions({
  name: "BatchOperationDialog"
});

// Props
interface Props {
  visible: boolean;
  selectedArticles: ArticleInfo[];
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  "update:visible": [value: boolean];
  refresh: [];
}>();

// 响应式数据
const loading = ref(false);
const operationFormRef = ref<FormInstance>();

// 操作表单
const operationForm = reactive<BatchOperationParams>({
  articleIds: [],
  operationType: "" as BatchOperationType,
  remark: "",
  reason: "",
  sendNotification: true
});

// 表单验证规则
const operationRules: FormRules = {
  operationType: [
    { required: true, message: "请选择操作类型", trigger: "change" }
  ],
  reason: [
    {
      validator: (rule, value, callback) => {
        if (needsReason.value && !value?.trim()) {
          callback(new Error("请输入操作原因"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

// 可用的操作选项
const availableOperations = computed(() => {
  if (props.selectedArticles.length === 0) return [];

  const selectedStatuses = props.selectedArticles.map(
    article => article.status
  );
  const availableTypes =
    ArticleManagementUtils.getAvailableBatchOperations(selectedStatuses);

  return BATCH_OPERATION_OPTIONS.filter(option =>
    availableTypes.includes(option.value)
  );
});

// 是否需要填写原因
const needsReason = computed(() => {
  return [
    BatchOperationType.REJECT,
    BatchOperationType.UNPUBLISH,
    BatchOperationType.DELETE
  ].includes(operationForm.operationType);
});

// 是否为高风险操作
const isHighRiskOperation = computed(() => {
  return [
    BatchOperationType.DELETE,
    BatchOperationType.REJECT,
    BatchOperationType.UNPUBLISH
  ].includes(operationForm.operationType);
});

// 监听选中文章变化
watch(
  () => props.selectedArticles,
  newArticles => {
    operationForm.articleIds = newArticles.map(article => article.id);
  },
  { immediate: true }
);

// 监听对话框显示状态
watch(
  () => props.visible,
  visible => {
    if (!visible) {
      // 重置表单
      operationForm.operationType = "" as BatchOperationType;
      operationForm.remark = "";
      operationForm.reason = "";
      operationForm.sendNotification = true;
    }
  }
);

// 处理操作类型变化
const handleOperationChange = () => {
  // 清空原因字段
  operationForm.reason = "";
};

// 获取操作描述
const getOperationDescription = (operationType: BatchOperationType): string => {
  const descriptions = {
    [BatchOperationType.APPROVE]: "将文章状态设置为已发布",
    [BatchOperationType.REJECT]: "拒绝文章并设置为审核拒绝状态",
    [BatchOperationType.PUBLISH]: "发布文章，用户可见",
    [BatchOperationType.UNPUBLISH]: "下架文章，用户不可见",
    [BatchOperationType.TOP]: "将文章置顶显示",
    [BatchOperationType.UNTOP]: "取消文章置顶状态",
    [BatchOperationType.DELETE]: "删除文章（可恢复）",
    [BatchOperationType.RESTORE]: "恢复已删除的文章"
  };
  return descriptions[operationType] || "";
};

// 获取预览标题
const getPreviewTitle = () => {
  const operation = BATCH_OPERATION_OPTIONS.find(
    option => option.value === operationForm.operationType
  );
  return `将对 ${props.selectedArticles.length} 篇文章执行"${operation?.label}"操作`;
};

// 获取预览描述
const getPreviewDescription = () => {
  const descriptions = {
    [BatchOperationType.APPROVE]: "文章将被审核通过并可以发布",
    [BatchOperationType.REJECT]: "文章将被审核拒绝，作者需要修改后重新提交",
    [BatchOperationType.PUBLISH]: "文章将被发布，用户可以正常访问",
    [BatchOperationType.UNPUBLISH]: "文章将被下架，用户无法访问",
    [BatchOperationType.TOP]: "文章将被置顶显示",
    [BatchOperationType.UNTOP]: "文章将取消置顶状态",
    [BatchOperationType.DELETE]: "文章将被删除（软删除，可恢复）",
    [BatchOperationType.RESTORE]: "文章将从删除状态恢复"
  };
  return descriptions[operationForm.operationType] || "";
};

// 获取预览类型
const getPreviewType = () => {
  const types = {
    [BatchOperationType.APPROVE]: "success",
    [BatchOperationType.REJECT]: "error",
    [BatchOperationType.PUBLISH]: "success",
    [BatchOperationType.UNPUBLISH]: "warning",
    [BatchOperationType.TOP]: "info",
    [BatchOperationType.UNTOP]: "info",
    [BatchOperationType.DELETE]: "error",
    [BatchOperationType.RESTORE]: "success"
  };
  return types[operationForm.operationType] || "info";
};

// 提交操作
const handleSubmit = async () => {
  if (!operationFormRef.value) return;

  try {
    await operationFormRef.value.validate();

    await ElMessageBox.confirm(
      `确认对 ${props.selectedArticles.length} 篇文章执行此操作吗？`,
      "确认批量操作",
      {
        type: "warning",
        dangerouslyUseHTMLString: true
      }
    );

    loading.value = true;
    await batchOperateArticlesApi(operationForm);

    ElMessage.success(MESSAGES.SUCCESS.BATCH_OPERATION);
    emit("refresh");
    handleCancel();
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量操作失败:", error);
      ElMessage.error(MESSAGES.ERROR.OPERATION_FAILED);
    }
  } finally {
    loading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  operationFormRef.value?.resetFields();
  dialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
// 响应式设计
@media (width <= 768px) {
  .batch-operation-dialog {
    .articles-list {
      max-height: 150px;

      .article-item {
        .article-meta {
          flex-wrap: wrap;
          gap: 4px;

          .el-divider {
            display: none;
          }
        }
      }
    }
  }
}

.batch-operation-dialog {
  .selected-articles,
  .operation-selection,
  .operation-preview,
  .risk-warning {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;

    .iconify {
      margin-right: 8px;
      color: #e6a23c;
    }
  }

  .articles-list {
    max-height: 200px;
    overflow-y: auto;

    .article-item {
      padding: 12px;
      margin-bottom: 8px;
      border: 1px solid #ebeef5;
      border-radius: 4px;

      &:last-child {
        margin-bottom: 0;
      }

      .article-info {
        .article-title {
          margin-bottom: 8px;
          font-size: 14px;
          font-weight: 500;
          line-height: 1.4;
          color: #303133;
        }

        .article-meta {
          display: flex;
          align-items: center;
          font-size: 12px;
          color: #909399;

          .author,
          .category {
            color: #606266;
          }
        }
      }
    }
  }

  // 操作选项样式优化
  .operation-option {
    display: flex !important;
    flex-direction: row !important;
    gap: 8px !important;
    align-items: center !important;
    width: 100% !important;
    padding: 8px 4px;
    cursor: pointer;
    border-radius: 6px;
    transition: all 0.3s ease;

    &:hover {
      background-color: #f5f7fa;
      transform: translateX(2px);
    }

    .option-icon {
      display: flex !important;
      flex-shrink: 0 !important; // 防止图标被压缩
      align-items: center !important;
      justify-content: center !important;
      width: 24px !important;
      height: 24px !important;
      border-radius: 4px;
      transition: all 0.3s ease;

      .iconify {
        font-size: 16px;
        transition: all 0.3s ease;
      }
    }

    .option-content {
      display: flex !important;
      flex: 1 !important;
      flex-direction: column !important;
      gap: 1px;
      justify-content: center !important;

      .option-label {
        margin: 0;
        font-size: 14px;
        font-weight: 500;
        line-height: 1.2;
        color: #303133;
      }

      .option-description {
        margin: 0;
        font-size: 11px;
        line-height: 1.2;
        color: #909399;
        word-wrap: break-word;
        opacity: 0.8;
      }
    }

    // 根据操作类型设置不同的颜色主题
    &[data-type="success"] {
      .option-icon {
        color: #67c23a;
        background-color: #f0f9ff;
      }

      &:hover .option-icon {
        color: white;
        background-color: #67c23a;
        box-shadow: 0 2px 8px rgb(103 194 58 / 30%);
      }
    }

    &[data-type="primary"] {
      .option-icon {
        color: #409eff;
        background-color: #ecf5ff;
      }

      &:hover .option-icon {
        color: white;
        background-color: #409eff;
        box-shadow: 0 2px 8px rgb(64 158 255 / 30%);
      }
    }

    &[data-type="warning"] {
      .option-icon {
        color: #e6a23c;
        background-color: #fdf6ec;
      }

      &:hover .option-icon {
        color: white;
        background-color: #e6a23c;
        box-shadow: 0 2px 8px rgb(230 162 60 / 30%);
      }
    }

    &[data-type="danger"] {
      .option-icon {
        color: #f56c6c;
        background-color: #fef0f0;
      }

      &:hover .option-icon {
        color: white;
        background-color: #f56c6c;
        box-shadow: 0 2px 8px rgb(245 108 108 / 30%);
      }
    }

    &[data-type="info"] {
      .option-icon {
        color: #909399;
        background-color: #f4f4f5;
      }

      &:hover .option-icon {
        color: white;
        background-color: #909399;
        box-shadow: 0 2px 8px rgb(144 147 153 / 30%);
      }
    }
  }

  // 选择器下拉面板样式
  :deep(.el-select-dropdown) {
    .el-select-dropdown__item {
      display: flex !important;
      align-items: center !important;
      height: auto !important;
      min-height: 44px !important;
      padding: 4px 12px !important;
      line-height: normal !important;

      // 强制覆盖Element Plus的默认样式
      .operation-option {
        display: flex !important;
        flex-direction: row !important;
        gap: 8px !important;
        align-items: center !important;
        width: 100% !important;

        .option-icon {
          display: flex !important;
          flex-shrink: 0 !important;
          align-items: center !important;
          justify-content: center !important;
          width: 24px !important;
          height: 24px !important;
        }

        .option-content {
          display: flex !important;
          flex: 1 !important;
          flex-direction: column !important;
          justify-content: center !important;
        }
      }

      &.is-selected {
        background-color: #f0f9ff;

        .operation-option {
          background-color: transparent;

          .option-label {
            font-weight: 600;
            color: #409eff;
          }
        }
      }

      &:hover {
        background-color: transparent;
      }
    }
  }

  .preview-content {
    display: flex;
    align-items: center;
    min-height: 80px;

    .no-operation {
      width: 100%;
      text-align: center;
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
